import 'package:flutter_bsbdj/bean/mei_tui.dart';

import 'data_base.dart';

class ImageTable {
  static ImageTable _novelTable;

  static ImageTable getInstance() {
    if (_novelTable == null) {
      _novelTable = ImageTable();
    }
    return _novelTable;
  }

  Future<int> insertInfo(MeituItem info) async {
    return insertMeitu(null,info.createdAt,info.desc,info.source,info.who,info.type,info.publishedAt,info.url);
  }

  void insertList(List<MeituItem> lists){
    for(var item in lists){
      insertInfo(item);
    }
  }

  Future<int> insertMeitu(
      int id,
      String url,
      String createdAt,
      String desc,
      String source,
      String who,
      String type,
      String publishedAt) async {
    String sql =
        "INSERT INTO Meitu(id,createdAt,desc,source,who,type,publishedAt,url) "
        "VALUES (?,?,?,?,?,?,?,?)";
    DataBaseUtil.getInstance().getDataBase().transaction((trans) async {
      int t = 0;
      t = await trans.rawInsert(sql, [
        null,
        url,
        createdAt,
        desc,
        source,
        who,
        type,
        publishedAt
      ]);
      return t;
    });
    return 0;
  }

  Future<List<MeituItem>> getAllInfo() async {
    var info = await DataBaseUtil.getInstance().getDataBase().query("Meitu");
    if (info == null) {
      return null;
    } else {
      List<MeituItem> novels = [];
      for (var item in info) {
        novels.add(MeituItem.fromJson(item));
      }
      return novels;
    }
  }

  void deleteById(int id, Function fun) async {
    var t = await DataBaseUtil.getInstance()
        .getDataBase()
        .delete("Meitu", where: "id=?", whereArgs: [id]);
    fun(t);
  }

  void deleteByIds(List<int> ids, Function fun) {
    for (var t in ids) {
      deleteById(t, (value) {
        print("delete $value");
      });
    }
    fun();
  }
}
